package com.youxin.third.auth.config.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TResult;
import com.youxin.common.constant.RedisKey;
import com.youxin.context.BaseContextConstants;
import com.youxin.context.BaseContextHandler;
import com.youxin.utils.StrHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Optional;

/**
 * description: AdminInterceptor <br>
 * date: 2020/3/8 12:08 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Component
public class AdminInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AdminInterceptor.class);

    @Resource
    @Lazy
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String account = getHeader(request, BaseContextConstants.JWT_KEY_ACCOUNT);
        if(StringUtils.isEmpty(account)){
            returnJson(response);
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    private String getHeader(HttpServletRequest request, String name) {
        String value = request.getHeader(name);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return StrHelper.decode(value);
    }

    private void returnJson(HttpServletResponse response){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            writer = response.getWriter();
            TResult result =TResult.build(BaseResultCode.COMMON_FAIL,"您无权限访问此操作");
            writer.print(JSONObject.toJSONString(result));
        } catch (IOException e){
            logger.error("拉截器异常",e);
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}
